package br.com.montadora.abc.dao;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */



import br.com.montadora.abc.util.HibernateUtil;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Order;


/**
 *
 * @author Aurelio
 */
public class DAOGenerico {
    protected static DAOGenerico instance = new DAOGenerico();
    
    protected DAOGenerico(){
    }
    
    /**
     * @return the instance
     */
    public static DAOGenerico getInstance() {
        return instance;
    }

    public void gravar(Object obj) throws HibernateException {
        Session session = HibernateUtil.getSession();
        Transaction transaction = session.beginTransaction();
        session.save(obj);
        transaction.commit();
        session.close();
    }
    public void alterar(Object obj) throws HibernateException {
        Session session = HibernateUtil.getSession();
        Transaction transaction = session.beginTransaction();
        session.update(obj);
        transaction.commit();
        session.close();
    }
    public void excluir(Object obj) throws HibernateException {
        Session session = HibernateUtil.getSession();
        Transaction transaction = session.beginTransaction();
        session.delete(obj);
        transaction.commit();
        session.close();
    }
    public List carregarTudoOrdenado(Class clas, String ordem) throws HibernateException {
        Session session = HibernateUtil.getSession();
        Criteria criteria = session.createCriteria(clas);
        criteria.addOrder(Order.asc(ordem));
        List lista = criteria.list();
        session.close();
        return lista;
    }

    public Object carregarUm(int id, Class clas) throws HibernateException {
        Session session = HibernateUtil.getSession();
        Transaction transaction = session.beginTransaction();
        Criteria criteria = session.createCriteria(clas);
        criteria.add(Expression.eq("id", id));
        Object obj = criteria.uniqueResult();
        transaction.commit();
        session.close();
        return obj;
    }

    public List pesquisarPorAtributo(Class clas,  String valor, String atributo, String ordem) throws HibernateException {
        Session session = HibernateUtil.getSession();
        Criteria criteria = session.createCriteria(clas);
        criteria.add(Expression.like(atributo, valor+"%"));
        criteria.addOrder(Order.asc(ordem));
        List lista = criteria.list();
        session.close();
        return lista;
    }

}
